/**
 * 销售订单 - 新增或编辑界面
 * 
 * @author linbo
 */
Ext.define("PSI.BillRelation.RSOEditForm", {
	extend : "Ext.window.Window",

	config : {
		parentForm : null,
		entity : null,
        permission : null
	},

	/**
	 * 初始化组件
	 */
	initComponent : function() {
		var me = this;
		me.__readOnly = false;
		var entity = me.getEntity();
		this.adding = entity == null;

		Ext.apply(me, {
			title : entity == null ? "新建销售关联订单" : "编辑销售关联订单",
			modal : true,
			onEsc : Ext.emptyFn,
			maximized : true,
			width : 1000,
			height : 600,
			layout : "border",
			// defaultFocus : "editSupplier",
			tbar : ["-", {
						text : "保存",
						id : "buttonSave",
						iconCls : "PSI-button-ok",
						handler : me.onOK,
						scope : me
					}, "-", {
						text : "取消",
						id : "buttonCancel",
						iconCls : "PSI-button-cancel",
						handler : function() {
							if (me.__readonly) {
								me.close();
								return;
							}

							PSI.MsgBox.confirm("请确认是否取消当前操作？", function() {
										me.close();
									});
						},
						scope : me
					}],
			items : [
					{
						region : "center",
                        layout : 'border',
						border : 0,
						bodyPadding : 10,
						items : [
                            {
                                region : "north",
                                height : 60,
                                layout : "fit",
                                border : 0,
                                title : "已关联列表",
                                collapsible : true,
                                layout : {
                                    type : "table",
                                    columns : 4
                                },
                                items : me.getDo1()
                            },
                            {
                                region : "north",
                                height : "35%",
                                split : true,
                                layout : "fit",
                                border : 0,
                                items : [me.getSOGrid()]
                            },
                            {
                                region : "center",
                                layout : "fit",
                                border : 0,
                                items : [me.getDetail2Grid()]
                            },
                            // {
                            //     region : "north",
                            //     height : 60,
                            //     // layout : "fit",
                            //     border : 0,
                            //     title : "未关联列表",
                            //     collapsible : true,
                            //     layout : {
                            //         type : "table",
                            //         columns : 4
                            //     },
                            //     items : me.getDo2()
                            // },
                            // {
                            //     region : "north",
                            //     height : 90,
                            //     // layout : "fit",
                            //     border : 0,
                            //     title : "查询条件",
                            //     collapsible : true,
                            //     layout : {
                            //         type : "table",
                            //         columns : 4
                            //     },
                            //     items : me.getQueryCmp()
                            // },
                            // {
                            //     region : "center",
                            //     layout : "fit",
                            //     border : 0,
                            //     items : [me.getMainGrid()]
                            // }
                            ]
					},
					{
						region : "north",
						id : "editForm",
						layout : {
							type : "table",
							columns : 4
						},
						height : 50,
						bodyPadding : 10,
						border : 0,
						items : [{
									xtype : "hidden",
									id : "hiddenId",
									name : "id",
									value : entity == null ? null : entity
											.get("id")
								}, {
									id : "editRef",
									labelWidth : 60,
									labelAlign : "right",
									labelSeparator : "",
									fieldLabel : "关联单号",
									xtype : "displayfield",
									value : "<span style='color:red'>保存后自动生成</span>"
								}, {
                                    id : "editRef2",
                                    labelWidth : 60,
                                    labelAlign : "right",
                                    labelSeparator : "",
                                    fieldLabel : "总销售计价",
                                    xtype : "displayfield",
                                    value : "<span style='color:red'>保存后自动计算</span>"
                                }]
					}],
			listeners : {
				show : {
					fn : me.onWndShow,
					scope : me
				},
				close : {
					fn : me.onWndClose,
					scope : me
				}
			}
		});

		me.callParent(arguments);

		me.__editorList = [];

		// me.refreshMainGrid();
		me.refreshDetail2Grid();
	},

	onWindowBeforeUnload : function(e) {
		return (window.event.returnValue = e.returnValue = '确认离开当前页面？');
	},

	onWndClose : function() {
		Ext.get(window).un('beforeunload', this.onWindowBeforeUnload);
        this.parentForm.refreshMainGrid();
	},

	onWndShow : function() {
		Ext.get(window).on('beforeunload', this.onWindowBeforeUnload);

        var me = this;
        if(me.entity !=null){
			me.loadPOGrid();
        }

	},
	loadPOGrid : function (selectData) {
        var me = this;
        var el = me.getEl() || Ext.getBody();

        if(me.entity){
            el.mask(PSI.Const.LOADING);
            Ext.Ajax.request({
                url : PSI.Const.BASE_URL + "Home/BillRelation/rsoBillInfo",
                params : {
                    id : Ext.getCmp("hiddenId").getValue()
                },
                method : "POST",
                callback : function(options, success, response) {
                    el.unmask();

                    if (success) {
                        var data = Ext.JSON.decode(response.responseText);

                        if (data.ref) {
                            Ext.getCmp("editRef").setValue(data.ref);
                        }
                        if(data.sumSum){
                            Ext.getCmp("editRef2").setValue(data.sumSum);
                        }
                        me.__taxRate = data.taxRate;

                        var store = me.getSOGrid().getStore();
                        store.removeAll();
                        if (data.items) {
                            store.add(data.items);
                        }
                        if (store.getCount() == 0) {
                            store.add({
                                taxRate : me.__taxRate
                            });
                        }

                        if (data.billStatus && data.billStatus != 0) {
                            me.setBillReadonly();

                        }
                    }
                }
            });
        }else {
            if(selectData.billStatus < 1){
                PSI.MsgBox.showInfo("不能关联未审核订单");
                return;
            }
            me.getSOGrid().getStore().add(selectData);
        }
    },

    /**
     * 已关联订单操作按钮
     */
    getDo1 : function() {
        var me = this;
        return [ {
            xtype : "container",
            items : [ {
                xtype : "button",
                text : "添加关联订单",
                width : 100,
                margin : "5, 0, 0, 10",
                iconCls : "PSI-button-add",
                handler : me.onAddRPO,
                scope : me
            },{
                xtype : "button",
                text : "移除关联订单",
                width : 100,
                margin : "5, 0, 0, 10",
                iconCls : "PSI-button-delete",
                handler : me.onRemoveRPO,
                scope : me
            }]
        }];
    },

    /**
     * 未关联订单操作按钮
     */
    getDo2 : function() {
        var me = this;
        return [ {
            xtype : "container",
            items : [{
                xtype : "button",
                text : "关联销售订单",
                width : 100,
                margin : "5 0 0 10",
                iconCls : "PSI-button-add",
                handler : me.onAddRPO,
                scope : me
            }]
        }];
    },

	onOK : function() {
		var me = this;
		Ext.getBody().mask("正在保存中...");
		Ext.Ajax.request({
			url : PSI.Const.BASE_URL + "Home/BillRelation/editRSOBill",
			method : "POST",
			params : {
				jsonStr : me.getSaveData()
			},
			callback : function(options, success, response) {
				Ext.getBody().unmask();

				if (success) {
					var data = Ext.JSON.decode(response.responseText);
					if (data.success) {
						PSI.MsgBox.showInfo("成功保存数据", function() {
									me.close();
									me.getParentForm().refreshMainGrid(data.id);
								});
					} else {
						PSI.MsgBox.showInfo(data.msg);
					}
				}
			}
		});

	},

	onEditSpecialKey : function(field, e) {
		if (e.getKey() === e.ENTER) {
			var me = this;
			var id = field.getId();
			for (var i = 0; i < me.__editorList.length; i++) {
				var editorId = me.__editorList[i];
				if (id === editorId) {
					var edit = Ext.getCmp(me.__editorList[i + 1]);
					edit.focus();
					edit.setValue(edit.getValue());
				}
			}
		}
	},

	onLastEditSpecialKey : function(field, e) {
		if (this.__readonly) {
			return;
		}

		if (e.getKey() == e.ENTER) {
			var me = this;
			var store = me.getSOGrid().getStore();
			if (store.getCount() == 0) {
				store.add({
							taxRate : me.__taxRate
						});
			}
			me.getSOGrid().focus();
			me.__cellEditing.startEdit(0, 1);
		}
	},

	getSOGrid : function() {
		var me = this;
		if (me.__goodsGrid) {
			return me.__goodsGrid;
		}
		var modelName = "PSISOBillDetail_EditForm";
		Ext.define(modelName, {
					extend : "Ext.data.Model",
					fields : ["id", "bill_type_id" ,"billType" ,"ref", "customerName", "contact", "tel",
                        "fax", "inputUserName", "bizUserName",
                        "billStatus", "goodsMoney", "dateCreated",
                        "receivingType", "tax", "moneyWithTax", "dealDate",
                        "dealAddress", "orgName", "confirmUserName",
                        "confirmDate", "billMemo"]
				});
		var store = Ext.create("Ext.data.Store", {
					autoLoad : false,
					model : modelName,
					data : []
				});

		me.__cellEditing = Ext.create("PSI.UX.CellEditing", {
					clicksToEdit : 1,
					listeners : {
						edit : {
							fn : me.cellEditingAfterEdit,
							scope : me
						}
					}
				});

		me.__goodsGrid = Ext.create("Ext.grid.Panel", {

							viewConfig : {
								enableTextSelection : true
							},
							features : [{
										ftype : "summary"
									}],
							plugins : [me.__cellEditing],
							columnLines : true,
							columns : [{
                                xtype : "rownumberer",
                                width : 50
                            }, {
                                header : "状态",
                                dataIndex : "billStatus",
                                menuDisabled : true,
                                sortable : false,
                                width : 60,
                                renderer : function(value) {
                                    if (value == 0) {
                                        return "<span style='color:red'>待审核</span>";
                                    } else if (value == 1000) {
                                        return "已审核";
                                    } else {
                                        return "";
                                    }
                                }
                            }, {
                                header : "销售订单号",
                                dataIndex : "ref",
                                width : 110,
                                menuDisabled : true,
                                sortable : false
                            }, {
                                header : "订单类型",
                                dataIndex : "billType",
                                menuDisabled : true,
                                sortable : false
                            }, {
                                header : "交货日期",
                                dataIndex : "dealDate",
                                menuDisabled : true,
                                sortable : false
                            }, {
                                header : "交货地址",
                                dataIndex : "dealAddress",
                                menuDisabled : true,
                                sortable : false
                            }, {
                                header : "客户",
                                dataIndex : "customerName",
                                width : 300,
                                menuDisabled : true,
                                sortable : false
                            }, {
                                header : "客户联系人",
                                dataIndex : "contact",
                                menuDisabled : true,
                                sortable : false
                            }, {
                                header : "客户电话",
                                dataIndex : "tel",
                                menuDisabled : true,
                                sortable : false
                            }, {
                                header : "客户传真",
                                dataIndex : "fax",
                                menuDisabled : true,
                                sortable : false
                            }, {
                                header : "销售金额",
                                dataIndex : "goodsMoney",
                                menuDisabled : true,
                                sortable : false,
                                align : "right",
                                xtype : "numbercolumn",
                                format: '0,0.0000',
                                width : 150
                            }, {
                                header : "税金",
                                dataIndex : "tax",
                                menuDisabled : true,
                                sortable : false,
                                align : "right",
                                xtype : "numbercolumn",
                                format: '0,0.0000',
                                width : 150
                            }, {
                                header : "价税合计",
                                dataIndex : "moneyWithTax",
                                menuDisabled : true,
                                sortable : false,
                                align : "right",
                                xtype : "numbercolumn",
                                format: '0,0.0000',
                                width : 150
                            }, {
                                header : "收款方式",
                                dataIndex : "receivingType",
                                menuDisabled : true,
                                sortable : false,
                                width : 100,
                                renderer : function(value) {
                                    if (value == 0) {
                                        return "记应收账款";
                                    } else if (value == 1) {
                                        return "现金收款";
                                    } else {
                                        return "";
                                    }
                                }
                            }, {
                                header : "业务员",
                                dataIndex : "bizUserName",
                                menuDisabled : true,
                                sortable : false
                            }, {
                                header : "组织机构",
                                dataIndex : "orgName",
                                menuDisabled : true,
                                sortable : false
                            }, {
                                header : "制单人",
                                dataIndex : "inputUserName",
                                menuDisabled : true,
                                sortable : false
                            }, {
                                header : "制单时间",
                                dataIndex : "dateCreated",
                                menuDisabled : true,
                                sortable : false,
                                width : 140
                            }, {
                                header : "审核人",
                                dataIndex : "confirmUserName",
                                menuDisabled : true,
                                sortable : false
                            }, {
                                header : "审核时间",
                                dataIndex : "confirmDate",
                                menuDisabled : true,
                                sortable : false,
                                width : 140
                            }, {
                                header : "备注",
                                dataIndex : "billMemo",
                                menuDisabled : true,
                                sortable : false
                            }],
					store : store,
					listeners : {
						cellclick : function() {
							return !me.__readonly;
						}
					}
				});

		return me.__goodsGrid;
	},
	__setGoodsInfo : function(data) {
		var me = this;
		var item = me.getSOGrid().getSelectionModel().getSelection();
		if (item == null || item.length != 1) {
			return;
		}
		var goods = item[0];

		goods.set("goodsId", data.id);
		goods.set("goodsCode", data.code);
		goods.set("goodsName", data.name);
		goods.set("unitName", data.unitName);
		goods.set("goodsSpec", data.spec);

		// 设置建议采购价
		goods.set("goodsPrice", data.purchasePrice);

		me.calcMoney(goods);
	},
	cellEditingAfterEdit : function(editor, e) {
		var me = this;

		if (me.__readonly) {
			return;
		}

		var fieldName = e.field;
		var goods = e.record;
		var oldValue = e.originalValue;

		if (fieldName == "moneyWithTax") {
			if (goods.get(fieldName) != (new Number(oldValue)).toFixed(2)) {
				me.calcTax(goods);
			}
			var store = me.getSOGrid().getStore();
			if (e.rowIdx == store.getCount() - 1) {
				store.add({
							taxRate : me.__taxRate
						});
			}
			e.rowIdx += 1;
			me.getSOGrid().getSelectionModel().select(e.rowIdx);
			me.__cellEditing.startEdit(e.rowIdx, 1);
		} else if (fieldName == "taxRate") {
			if (goods.get(fieldName) != (new Number(oldValue)).toFixed(2)) {
				me.calcMoneyWithTax(goods);
			}
		} /*else if (fieldName == "goodsMoney") {
			if (goods.get(fieldName) != (new Number(oldValue)).toFixed(2)) {
				me.calcPrice(goods);
			}
		} else if (fieldName == "goodsCount") {
			if (goods.get(fieldName) != oldValue) {
				me.calcMoney(goods);
			}
		} else if (fieldName == "goodsPrice") {
			if (goods.get(fieldName) != (new Number(oldValue)).toFixed(2)) {
				me.calcMoney(goods);
			}
		} else if (fieldName == "goodsPriceTax") {
			if (goods.get(fieldName) != (new Number(oldValue)).toFixed(2)) {
				me.calcPriceWithTax(goods);
			}
		}*/
	},

	calcTax : function(goods) {
		if (!goods) {
			return;
		}
		//var taxRate = goods.get("taxRate") / 100;
		//var tax = goods.get("moneyWithTax") * taxRate / (1 + taxRate);
		/*var taxRate = goods.get("tax") / (goods.get("moneyWithTax") - goods.get("tax"))
		 * 100;*/
		//goods.set("tax", tax);
		
		goods.set("goodsMoney", goods.get("moneyWithTax") / (1 + goods.get("taxRate") / 100));
		goods.set("tax", goods.get("moneyWithTax") - goods.get("goodsMoney"));
		goods.set("goodsPrice", goods.get("goodsMoney") / goods.get("goodsCount"));
		goods.set("goodsPriceTax", goods.get("goodsPrice") * (1 + goods.get("taxRate") / 100));
		
	},

	calcMoneyWithTax : function(goods) {
		if (!goods) {
			return;
		}
		//确定数量，单价，税率
		//goods.set("taxRate", taxRate);
		
		goods.set("goodsPriceTax", goods.get("goodsPrice") * (1 + goods.get("taxRate") / 100));
		goods.set("goodsMoney", goods.get("goodsPrice") * goods.get("goodsCount"));
		goods.set("tax", goods.get("goodsPrice") * (goods.get("taxRate") / 100) * goods.get("goodsCount"));
		goods.set("moneyWithTax", goods.get("goodsMoney") + goods.get("tax"));
	},

	calcMoney : function(goods) {
		if (!goods) {
			return;
		}

		goods.set("goodsMoney", goods.get("goodsCount")
						* goods.get("goodsPrice"));
		goods.set("tax", goods.get("goodsMoney") * goods.get("taxRate") / 100);
		goods.set("moneyWithTax", goods.get("goodsMoney") + goods.get("tax"));
	},

	calcPrice : function(goods) {
		if (!goods) {
			return;
		}

		var goodsCount = goods.get("goodsCount");
		if (goodsCount && goodsCount != 0) {
			goods.set("goodsPrice", goods.get("goodsMoney")
							/ goods.get("goodsCount"));
		}
	},

	calcPriceWithTax : function(goods) {
		if (!goods) {
			return;
		}

		var goodsCount = goods.get("goodsCount");
		//goods.get("taxRate", taxRate);
		//goods.set("moneyWithTax", goods.get("goodsMoney") + goods.get("tax"));
		if (goodsCount && goodsCount != 0) {
			//计算税价合计
			goods.set("moneyWithTax", goodsCount * goods.get("goodsPriceTax"));
			
			goods.set("goodsMoney", goods.get("moneyWithTax") / (1 + goods.get("taxRate") / 100));
			//计算单价
			goods.set("goodsPrice", goods.get("goodsMoney") / goodsCount);
			goods.set("tax", goods.get("moneyWithTax") - goods.get("goodsMoney"));

		}
	},

	getSaveData : function() {
    	var me = this;
    	if(me.entity !=null){
            var result = {
                id : Ext.getCmp("hiddenId").getValue(),
                items : []
            };
		}else{
            var result = {
                items : []
            };
            var store = this.getSOGrid().getStore();
            for (var i = 0; i < store.getCount(); i++) {
                var item = store.getAt(i);
                result.items.push({bill_id : item.get("id")});
            }
		}

		return Ext.JSON.encode(result);
	},

	setBillReadonly : function() {
		var me = this;
		me.__readonly = true;
		me.setTitle("查看销售关联订单");
		// Ext.getCmp("buttonSave").setDisabled(true);
		Ext.getCmp("buttonCancel").setText("关闭");

	},

	__setSupplierExtData : function(data) {
		Ext.getCmp("editDealAddress").setValue(data.address_shipping);
		Ext.getCmp("editTel").setValue(data.tel01);
		Ext.getCmp("editFax").setValue(data.fax);
		Ext.getCmp("editContact").setValue(data.contact01);
	}
    ,

    __setBillTypeExtData : function(data) {

    },
    onAddRPO : function(data) {

        var me = this;

        var form = Ext.create("PSI.BillRelation.SOEditBillChoiceForm", {
            parentForm : me,
            entity : me.entity
        });
        form.show();

        // var me = this;
        //
        // if(me.entity !=null){
		// 	var item = me.getMainGrid().getSelectionModel().getSelection();
		// 	if (item == null || item.length != 1) {
		// 		PSI.MsgBox.showInfo("没有选择要关联的销售订单");
		// 		return;
		// 	}
		// 	var bill = item[0];
        //
		// 	console.log(me.entity.data.id);
        //
		// 	var data = {
		// 		bill_id : bill.data.id,
		// 		relation_id : me.entity.data.id,
		// 	};
        //
		// 	Ext.getBody().mask("正在保存中...");
		// 	Ext.Ajax.request({
		// 		url : PSI.Const.BASE_URL + "Home/BillRelation/addRSORelation",
		// 		method : "POST",
		// 		params : {
		// 			jsonStr : Ext.JSON.encode(data)
		// 		},
		// 		callback : function(options, success, response) {
		// 			Ext.getBody().unmask();
        //
		// 			if (success) {
		// 				var data = Ext.JSON.decode(response.responseText);
		// 				if (data.success) {
		// 					PSI.MsgBox.showInfo("关联成功", function() {
		// 						me.loadPOGrid();
		// 						me.refreshMainGrid();
         //                        me.refreshDetail2Grid();
		// 					});
		// 				} else {
		// 					PSI.MsgBox.showInfo(data.msg);
		// 				}
		// 			}
		// 		}
		// 	});
        // }else{
         //    var item = me.getMainGrid().getSelectionModel().getSelection();
         //    if (item == null || item.length != 1) {
         //        PSI.MsgBox.showInfo("没有选择要关联的销售订单");
         //        return;
         //    }
         //    if(item[0].data.billStatus < 1){
         //        PSI.MsgBox.showInfo("不能关联未审核订单");
         //        return;
         //    }
         //    me.getSOGrid().getStore().add(item[0].data);
         //    me.refreshMainGrid();
         //    me.refreshDetail2Grid();
		// }
    },
    onRemoveRPO : function(data) {
        var me = this;
        var item = me.getSOGrid().getSelectionModel().getSelection();
        if (item == null || item.length != 1) {
            PSI.MsgBox.showInfo("没有选择要移除的销售订单");
            return;
        }

        var bill = item[0];

        if(me.entity !=null ){
            var data = {
                bill_id : bill.data.id,
                relation_id : me.entity.data.id,
            };

            Ext.getBody().mask("正在移除中...");
            Ext.Ajax.request({
                url : PSI.Const.BASE_URL + "Home/BillRelation/removeRSORelation",
                method : "POST",
                params : {
                    jsonStr : Ext.JSON.encode(data)
                },
                callback : function(options, success, response) {
                    Ext.getBody().unmask();

                    if (success) {
                        var data = Ext.JSON.decode(response.responseText);
                        if (data.success) {
                            PSI.MsgBox.showInfo("移除成功", function() {
                                me.loadPOGrid();
                                // me.refreshMainGrid();
                                me.refreshDetail2Grid();
                            });
                        } else {
                            PSI.MsgBox.showInfo(data.msg);
                        }
                    }
                }
            });
		}else{
        	me.getSOGrid().getStore().remove(item);
            // me.refreshMainGrid();
            me.refreshDetail2Grid();
		}
    },

    /**
     * 销售订单主表
     */
    getMainGrid : function() {
        var me = this;
        if (me.__mainGrid) {
            return me.__mainGrid;
        }

        var modelName = "PSISOBill";
        Ext.define(modelName, {
            extend : "Ext.data.Model",
            fields : ["id", "bill_type_id" ,"billType" ,"ref", "customerName", "contact", "tel",
                "fax", "inputUserName", "bizUserName",
                "billStatus", "goodsMoney", "dateCreated",
                "receivingType", "tax", "moneyWithTax", "dealDate",
                "dealAddress", "orgName", "confirmUserName",
                "confirmDate", "billMemo"]
        });
        var store = Ext.create("Ext.data.Store", {
            autoLoad : false,
            model : modelName,
            data : [],
            pageSize : 20,
            proxy : {
                type : "ajax",
                actionMethods : {
                    read : "POST"
                },
                url : PSI.Const.BASE_URL + "Home/BillRelation/rsoEditBillList",
                reader : {
                    root : 'dataList',
                    totalProperty : 'totalCount'
                }
            }
        });
        store.on("beforeload", function() {
            store.proxy.extraParams = me.getQueryParam();
        });
        store.on("load", function(e, records, successful) {
            if (successful) {
                me.gotoMainGridRecord(me.__lastId);
            }
        });

        me.__mainGrid = Ext.create("Ext.grid.Panel", {
            viewConfig : {
                enableTextSelection : true
            },
            border : 0,
            columnLines : true,
            columns : [{
                xtype : "rownumberer",
                width : 50
            }, {
                header : "状态",
                dataIndex : "billStatus",
                menuDisabled : true,
                sortable : false,
                width : 60,
                renderer : function(value) {
                    if (value == 0) {
                        return "<span style='color:red'>待审核</span>";
                    } else if (value == 1000) {
                        return "已审核";
                    } else {
                        return "";
                    }
                }
            }, {
                header : "销售订单号",
                dataIndex : "ref",
                width : 110,
                menuDisabled : true,
                sortable : false
            }, {
                header : "订单类型",
                dataIndex : "billType",
                menuDisabled : true,
                sortable : false
            }, {
                header : "交货日期",
                dataIndex : "dealDate",
                menuDisabled : true,
                sortable : false
            }, {
                header : "交货地址",
                dataIndex : "dealAddress",
                menuDisabled : true,
                sortable : false
            }, {
                header : "客户",
                dataIndex : "customerName",
                width : 300,
                menuDisabled : true,
                sortable : false
            }, {
                header : "客户联系人",
                dataIndex : "contact",
                menuDisabled : true,
                sortable : false
            }, {
                header : "客户电话",
                dataIndex : "tel",
                menuDisabled : true,
                sortable : false
            }, {
                header : "客户传真",
                dataIndex : "fax",
                menuDisabled : true,
                sortable : false
            }, {
                header : "销售金额",
                dataIndex : "goodsMoney",
                menuDisabled : true,
                sortable : false,
                align : "right",
                xtype : "numbercolumn",
                format: '0,0.0000',
                width : 150
            }, {
                header : "税金",
                dataIndex : "tax",
                menuDisabled : true,
                sortable : false,
                align : "right",
                xtype : "numbercolumn",
                format: '0,0.0000',
                width : 150
            }, {
                header : "价税合计",
                dataIndex : "moneyWithTax",
                menuDisabled : true,
                sortable : false,
                align : "right",
                xtype : "numbercolumn",
                format: '0,0.0000',
                width : 150
            }, {
                header : "收款方式",
                dataIndex : "receivingType",
                menuDisabled : true,
                sortable : false,
                width : 100,
                renderer : function(value) {
                    if (value == 0) {
                        return "记应收账款";
                    } else if (value == 1) {
                        return "现金收款";
                    } else {
                        return "";
                    }
                }
            }, {
                header : "业务员",
                dataIndex : "bizUserName",
                menuDisabled : true,
                sortable : false
            }, {
                header : "组织机构",
                dataIndex : "orgName",
                menuDisabled : true,
                sortable : false
            }, {
                header : "制单人",
                dataIndex : "inputUserName",
                menuDisabled : true,
                sortable : false
            }, {
                header : "制单时间",
                dataIndex : "dateCreated",
                menuDisabled : true,
                sortable : false,
                width : 140
            }, {
                header : "审核人",
                dataIndex : "confirmUserName",
                menuDisabled : true,
                sortable : false
            }, {
                header : "审核时间",
                dataIndex : "confirmDate",
                menuDisabled : true,
                sortable : false,
                width : 140
            }, {
                header : "备注",
                dataIndex : "billMemo",
                menuDisabled : true,
                sortable : false
            }],
            store : store,
            tbar : [{
                id : "rso_edit_pagingToobar",
                xtype : "pagingtoolbar",
                border : 0,
                store : store
            }, "-", {
                xtype : "displayfield",
                value : "每页显示"
            }, {
                id : "rso_edit_comboCountPerPage",
                xtype : "combobox",
                editable : false,
                width : 60,
                store : Ext.create("Ext.data.ArrayStore", {
                    fields : ["text"],
                    data : [["20"], ["50"], ["100"],
                        ["300"], ["1000"]]
                }),
                value : 20,
                listeners : {
                    change : {
                        fn : function() {
                            store.pageSize = Ext
                                .getCmp("rso_edit_comboCountPerPage")
                                .getValue();
                            store.currentPage = 1;
                            Ext.getCmp("rso_edit_pagingToobar")
                                .doRefresh();
                        },
                        scope : me
                    }
                }
            }, {
                xtype : "displayfield",
                value : "条记录"
            }],
            listeners : {
                select : {
                    fn : me.onMainGridSelect,
                    scope : me
                },
                itemdblclick : {
                    fn : me.onEditBill,
                    scope : me
                }
            }
        });

        return me.__mainGrid;
    },
    onMainGridSelect : function() {
        var me = this;
        var item = me.getMainGrid().getSelectionModel().getSelection();
        if (item == null || item.length != 1) {

            return;
        }
        var bill = item[0];

    },
    getQueryParam : function() {
        var me = this;

        var result = {
            billStatus : Ext.getCmp("rso_edit_editQueryBillStatus").getValue()
        };

        var ref = Ext.getCmp("rso_edit_editQueryRef").getValue();
        if (ref) {
            result.ref = ref;
        }

        var customerId = Ext.getCmp("rso_edit_editQueryCustomer").getIdValue();
        if (customerId) {
            result.customerId = customerId;
        }

        var fromDT = Ext.getCmp("rso_edit_editQueryFromDT").getValue();
        if (fromDT) {
            result.fromDT = Ext.Date.format(fromDT, "Y-m-d");
        }

        var toDT = Ext.getCmp("rso_edit_editQueryToDT").getValue();
        if (toDT) {
            result.toDT = Ext.Date.format(toDT, "Y-m-d");
        }

        var receivingType = Ext.getCmp("rso_edit_editQueryReceivingType").getValue();
        result.receivingType = receivingType;

        if(me.entity ==null){
            result.selectIds = '';
            var store = this.getSOGrid().getStore();
            for (var i = 0; i < store.getCount(); i++) {
                var item = store.getAt(i);
                result.selectIds += "'"+item.get("id")+"'";
                if(i!=store.getCount()-1){
                    result.selectIds += ",";
                }
            }
        }

        return result;
    },
    gotoMainGridRecord : function(id) {
        var me = this;
        var grid = me.getMainGrid();
        grid.getSelectionModel().deselectAll();
        var store = grid.getStore();
        if (id) {
            var r = store.findExact("id", id);
            if (r != -1) {
                grid.getSelectionModel().select(r);
            } else {
                grid.getSelectionModel().select(0);
            }
        } else {
            grid.getSelectionModel().select(0);
        }
    },
    /**
     * 查询条件
     */
    getQueryCmp : function() {
        var me = this;
        return [{
            id : "rso_edit_editQueryBillStatus",
            xtype : "combo",
            queryMode : "local",
            editable : false,
            valueField : "id",
            labelWidth : 60,
            labelAlign : "right",
            labelSeparator : "",
            fieldLabel : "状态",
            margin : "5, 0, 0, 0",
            store : Ext.create("Ext.data.ArrayStore", {
                fields : ["id", "text"],
                data : [[-1, "全部"], [0, "待审核"], [1000, "已审核"]]
            }),
            value : -1
        }, {
            id : "rso_edit_editQueryRef",
            labelWidth : 60,
            labelAlign : "right",
            labelSeparator : "",
            fieldLabel : "单号",
            margin : "5, 0, 0, 0",
            xtype : "textfield"
        }, {
            id : "rso_edit_editQueryFromDT",
            xtype : "datefield",
            margin : "5, 0, 0, 0",
            format : "Y-m-d",
            labelAlign : "right",
            labelSeparator : "",
            fieldLabel : "交货日期（起）"
        }, {
            id : "rso_edit_editQueryToDT",
            xtype : "datefield",
            margin : "5, 0, 0, 0",
            format : "Y-m-d",
            labelAlign : "right",
            labelSeparator : "",
            fieldLabel : "交货日期（止）"
        }, {
            id : "rso_edit_editQueryCustomer",
            xtype : "psi_customerfield",
            labelAlign : "right",
            labelSeparator : "",
            labelWidth : 60,
            margin : "5, 0, 0, 0",
            fieldLabel : "客户"
        }, {
            id : "rso_edit_editQueryReceivingType",
            labelAlign : "right",
            labelSeparator : "",
            fieldLabel : "收款方式",
            labelWidth : 60,
            margin : "5, 0, 0, 0",
            xtype : "combo",
            queryMode : "local",
            editable : false,
            valueField : "id",
            store : Ext.create("Ext.data.ArrayStore", {
                fields : ["id", "text"],
                data : [[-1, "全部"], [0, "记应收账款"], [1, "现金收款"]]
            }),
            value : -1
        }, {
            xtype : "container",
            items : [{
                xtype : "button",
                text : "查询",
                width : 100,
                margin : "5 0 0 10",
                iconCls : "PSI-button-refresh",
                handler : me.onQuery,
                scope : me
            }, {
                xtype : "button",
                text : "清空查询条件",
                width : 100,
                margin : "5, 0, 0, 10",
                handler : me.onClearQuery,
                scope : me
            }]
        }];
    },
    /**
     * 刷新销售订单主表记录
     */
    refreshMainGrid : function(id) {
        var me = this;

        Ext.getCmp("rso_edit_pagingToobar").doRefresh();
        me.__lastId = id;


    },
    /**
     * 查询
     */
    onQuery : function() {
        this.refreshMainGrid();
    },
    /**
     * 清除查询条件
     */
    onClearQuery : function() {
        var me = this;

        Ext.getCmp("rso_edit_editQueryBillStatus").setValue(-1);
        Ext.getCmp("rso_edit_editQueryRef").setValue(null);
        Ext.getCmp("rso_edit_editQueryFromDT").setValue(null);
        Ext.getCmp("rso_edit_editQueryToDT").setValue(null);
        Ext.getCmp("rso_edit_editQueryCustomer").clearIdValue();
        Ext.getCmp("rso_edit_editQueryReceivingType").setValue(-1);

        me.onQuery();
    },
    /**
     * 采购关联订单商品明细
     */
    getDetail2Grid : function() {
        var me = this;
        if (me.__detailGrid2) {
            return me.__detailGrid2;
        }

        var modelName = "PSIPOBillDetail2";
        Ext.define(modelName, {
            extend : "Ext.data.Model",
            fields : ["id", "goodsCode", "goodsName", "goodsSpec",
                "unitName", "goodsCount", "goodsMoney",
                "goodsPrice", "goodsPriceTax", "taxRate", "tax", "moneyWithTax"]
        });
        var store = Ext.create("Ext.data.Store", {
            autoLoad : false,
            model : modelName,
            data : []
        });

        me.__detailGrid2 = Ext.create("Ext.grid.Panel", {
            title : "采购关联订单明细",
            viewConfig : {
                enableTextSelection : true
            },
            columnLines : true,
            columns : [{
                xtype : "rownumberer",
                width : 50
            }, {
                header : "商品编码",
                dataIndex : "goodsCode",
                menuDisabled : true,
                sortable : false,
                width : 120
            }, {
                header : "商品名称",
                dataIndex : "goodsName",
                menuDisabled : true,
                sortable : false,
                width : 200
            }, {
                header : "规格型号",
                dataIndex : "goodsSpec",
                menuDisabled : true,
                sortable : false,
                width : 200
            }, {
                header : "销售数量1",
                dataIndex : "goodsCount",
                menuDisabled : true,
                sortable : false,
                align : "right"
            }, {
                header : "单位",
                dataIndex : "unitName",
                menuDisabled : true,
                sortable : false,
                width : 60
            }, {
                header : "销售单价",
                dataIndex : "goodsPrice",
                menuDisabled : true,
                sortable : false,
                align : "right",
                xtype : "numbercolumn",
                format: '0,0.0000',
                width : 150
            }, {
                header : "含税单价",
                dataIndex : "goodsPriceTax",
                menuDisabled : true,
                sortable : false,
                align : "right",
                xtype : "numbercolumn",
                format: '0,0.0000',
                width : 150
            }, {
                header : "销售金额",
                dataIndex : "goodsMoney",
                menuDisabled : true,
                sortable : false,
                align : "right",
                xtype : "numbercolumn",
                format: '0,0.0000',
                width : 150
            }, {
                header : "税率",
                dataIndex : "taxRate",
                menuDisabled : true,
                sortable : false,
                align : "right"
            }, {
                header : "税金",
                dataIndex : "tax",
                menuDisabled : true,
                sortable : false,
                align : "right",
                xtype : "numbercolumn",
                format: '0,0.0000',
                width : 150
            }, {
                header : "价税合计",
                dataIndex : "moneyWithTax",
                menuDisabled : true,
                sortable : false,
                align : "right",
                xtype : "numbercolumn",
                format: '0,0.0000',
                width : 150
            }],
            store : store
        });

        return me.__detailGrid2;
    },
    /**
     * 刷新采购订单明细记录
     */
    refreshDetail2Grid : function(id) {
        var me = this;
        me.getDetail2Grid().setTitle("采购关联订单明细");
        // var item = me.getMainGrid().getSelectionModel().getSelection();
        // if (item == null || item.length != 1) {
        //     return;
        // }
        var bill = me.entity;

        var selectIds = [];

        if(me.entity ==null){
            var store = this.getSOGrid().getStore();
            for (var i = 0; i < store.getCount(); i++) {
                var item = store.getAt(i);
                selectIds += "'"+item.get("id")+"'";
                if(i!=store.getCount()-1){
                    selectIds += ",";
                }
            }
        }else{
            var bill = me.entity;
        }
        var grid = me.getDetail2Grid();
        if(me.entity){
            grid.setTitle("销售商品明细 " );
            var param = {
                id : bill.get("id"),
                selectIds : selectIds
            };
        }else{
            grid.setTitle("销售商品明细");
            var param = {
                id : 0,
                selectIds : selectIds
            };
        }

        var r = {
            url : PSI.Const.BASE_URL + "Home/BillRelation/rsoBillDetail2List",
            params : param,
            method : "POST",
            callback : function(options, success, response) {
                var store = grid.getStore();

                store.removeAll();

                if (success) {
                    var data = Ext.JSON.decode(response.responseText);
                    store.add(data);

                    if (store.getCount() > 0) {
                        if (id) {
                            var r = store.findExact("id", id);
                            if (r != -1) {
                                grid.getSelectionModel().select(r);
                            }
                        }
                    }
                }

            }
        };
        Ext.Ajax.request(r);
    },
});